package cn.xxstudy.compose.material

import android.os.Bundle
import android.util.Log
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.fadeIn
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.material.*
import androidx.compose.material.MaterialTheme.shapes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cn.xxstudy.compose.ui.theme.ComposeDemoTheme
import kotlinx.coroutines.launch

/**
 * @author ：wuxinxi on 2021/3/5 .
 * @packages ：cn.xxstudy.compose.material .
 * TODO:简单组件
 */
class SimpleWidgetActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeDemoTheme {
                SimpleComponent()
            }
        }
    }
}

@Preview
@Composable
fun SimpleComponent() {
    val context = LocalContext.current as AppCompatActivity
    Scaffold(
        topBar = {
            TopAppBar(title = { Text(text = "常用组件的使用") }, navigationIcon = {
                IconButton(onClick = { context.finish() }) {
                    Icon(Icons.Filled.ArrowBack, "")
                }
            })
        },
        content = { SimpleContent() }
    )
}

@Composable
fun SimpleContent() {
    LazyColumn(
        verticalArrangement = Arrangement.spacedBy(15.dp),
        modifier = Modifier.padding(horizontal = 5.dp)
    ) {
        item { CheckBoxComponent() }
        item { CardComponent() }
        item { TriCheckBoxComponent() }
        item { CircularProgressIndicatorComponent() }
        item { LinearProgressIndicatorComponent() }
        item { DropdownMenuComponent() }
        item { ExtendFloatingActionButtonComponent() }
        item { OutlineButtonComponent() }
        item { OutlineTextFieldComponent() }
        item { ProviderTextStyleComponent() }
        item { RadioButtonComponent() }
        item { RadioButtonWithTextComponent() }
        item { ScrollableTabRowComponent() }
        item { SliderComponent() }
        item { SwipeToDismissList() }
        item { SwitchComponent() }
    }
}

@Composable
fun CheckBoxComponent() {
    var checkState = remember { mutableStateOf(true) }
    Checkbox(checked = checkState.value, onCheckedChange = { checkState.value = it })
}

/**
 * 多种状态的Checkbox 选中、未选中、未知
 */
@Composable
fun TriCheckBoxComponent() {
    var checkState = remember { mutableStateOf(ToggleableState(false)) }
    val state = remember { mutableStateOf(0) }
    TriStateCheckbox(state = checkState.value, onClick = {
        Log.d("Log", "state.value=${state.value}")
        when (state.value) {
            0 -> {
                checkState.value = ToggleableState.On
                ++state.value
            }
            1 -> {
                checkState.value = ToggleableState.Off
                ++state.value
            }
            else -> {
                checkState.value = ToggleableState.Indeterminate
                state.value = 0
            }
        }
    })
}

@Composable
fun CardComponent() {
    Card {
        Text(text = "Card text ...")
    }
}

/**
 *圆形进度指示器
 */
@Composable
fun CircularProgressIndicatorComponent() {
    var progress by remember { mutableStateOf(0.1f) }
    val animatedProgress by animateFloatAsState(
        targetValue = progress,
        animationSpec = ProgressIndicatorDefaults.ProgressAnimationSpec
    )
    Column {
        CircularProgressIndicator(progress = animatedProgress)
        Spacer(modifier = Modifier.requiredHeight(30.dp))
        OutlinedButton(onClick = {
            progress = if (progress < 1f) progress + .1f else 0.1f
        }) {
            Text(text = "模拟进度")
        }
    }
}

@Composable
fun LinearProgressIndicatorComponent() {
    var progress by remember { mutableStateOf(.1f) }
    val animatedProgress by animateFloatAsState(
        progress,
        ProgressIndicatorDefaults.ProgressAnimationSpec
    )
    Spacer(modifier = Modifier.requiredHeight(30.dp))
    Column(modifier = Modifier.fillMaxWidth()) {
        LinearProgressIndicator(progress = animatedProgress, modifier = Modifier.fillMaxSize())
        OutlinedButton(onClick = { progress = if (progress < 1f) progress + .1f else 0.1f }) {
            Text(text = "模拟进度")
        }
    }
}

/**
 *下拉菜单 ActionBar menu
 */
@Composable
fun DropdownMenuComponent() {
    var expandedState by remember { mutableStateOf(false) }
    Box(
        modifier = Modifier
            .fillMaxSize()
            .wrapContentSize(Alignment.TopStart)
    ) {
        IconButton(onClick = { expandedState = true }) {
            Icon(Icons.Filled.MoreVert, contentDescription = Icons.Filled.MoreVert.name)
        }
        DropdownMenu(expanded = expandedState, onDismissRequest = { expandedState = false }) {
            DropdownMenuItem(onClick = { expandedState = false }) {
                Text(text = "查询当前的记录")
            }
            DropdownMenuItem(onClick = { expandedState = false }) {
                Text(text = "查询前三天的记录")
            }
            DropdownMenuItem(onClick = { expandedState = false }) {
                Text(text = "查询一周内的记录")
            }
            DropdownMenuItem(onClick = { expandedState = false }) {
                Text(text = "查询一个月内的记录")
            }
        }
    }
}

/**
 *扩展的FloatingActionButton
 */
@Composable
fun ExtendFloatingActionButtonComponent() {
    ExtendedFloatingActionButton(
        text = { Text("扩展的FAB") },
        icon = { Icon(Icons.Filled.Favorite, Icons.Filled.Favorite.name) },
        onClick = { })
}

@Composable
fun IcnToggleButtonComponent() {
    var toggleState by remember { mutableStateOf(false) }
    IconToggleButton(modifier = Modifier.padding(10.dp), checked = toggleState, onCheckedChange = {
        toggleState = it
    }) {
        val tint by animateColorAsState(
            targetValue = if (toggleState) Color(0xFFE91E63) else Color(
                0xFF3F51B5
            )
        )
        Icon(Icons.Filled.Favorite, contentDescription = "", tint = tint)
    }
}

@Composable
fun OutlineButtonComponent() {
    OutlinedButton(modifier = Modifier.padding(10.dp), shape = shapes.large, onClick = { }) {
        Icon(Icons.Default.Delete, contentDescription = "")
        Text("确认删除")
    }
}

@Composable
fun OutlineTextFieldComponent() {
    val nameState = remember { mutableStateOf("") }
    val pwdState = remember { mutableStateOf("") }
    val isError = remember { mutableStateOf(false) }
    Column(
        modifier = Modifier
            .padding(horizontal = 5.dp)
            .fillMaxWidth()
    ) {
        TextField(
            value = nameState.value,
            onValueChange = { nameState.value = it },
            placeholder = { Text("用户名") },
            modifier = Modifier.fillMaxWidth(),
            leadingIcon = { Icon(Icons.Default.Person, "") },
            trailingIcon = {
                IconButton(onClick = { nameState.value = "" }) {
                    Icon(Icons.Default.Close, "")
                }
            },
            isError = isError.value,
            colors = TextFieldDefaults.textFieldColors(backgroundColor = Color.White),
            //单行显示，与maxLines冲突，后者将失效
            singleLine = true,
            //行数
            maxLines = 1,
        )
        Spacer(modifier = Modifier.requiredHeight(5.dp))
        OutlinedTextField(
            value = pwdState.value,
            onValueChange = { pwdState.value = it },
            modifier = Modifier.fillMaxWidth(),
            isError = isError.value,
            placeholder = { Text("密码") },
            leadingIcon = { Icon(Icons.Default.Lock, "") },
            trailingIcon = {
                IconButton(onClick = { pwdState.value = "" }) {
                    Icon(Icons.Default.Close, "")
                }
            },
            //获取焦点后label显示到Outline左上角
            label = { Text(text = "密码") },
            //密码
            visualTransformation = PasswordVisualTransformation()
        )
        Spacer(modifier = Modifier.requiredHeight(5.dp))
        ExtendedFloatingActionButton(
            text = { Text("登录") },
            onClick = {
                isError.value = nameState.value.isNullOrEmpty() || pwdState.value.isNullOrEmpty()
            },
            icon = { Icon(Icons.Default.Home, "") }, modifier = Modifier.fillMaxWidth(),
        )
        if (!isError.value) {
            Text(text = "登录成功")
        }
        Spacer(modifier = Modifier.requiredHeight(5.dp))
    }
}

@Composable
fun ProviderTextStyleComponent() {
    val scope = rememberCoroutineScope()
    val provideTextColorState = remember { mutableStateOf(Color.Green) }
    ProvideTextStyle(
        value = TextStyle(
            color = provideTextColorState.value,
            fontSize = 16.sp,
            fontWeight = FontWeight.Bold,
        )
    ) {
        Column(
            content = {
                Text(text = "ProvideTextStyle->下面的文字将与我样式保持一致")
                Text(text = "我与上面的样式保持一致")
                Text(text = "我与上面的样式保持一致<-ProvideTextStyle")
                Spacer(modifier = Modifier.requiredHeight(5.dp))
                TextButton(onClick = { scope.launch { provideTextColorState.value = Color.Red } }) {
                    Text("点我变颜色")
                }
            }
        )
    }
}

@Composable
fun RadioButtonComponent() {
    val state = remember { mutableStateOf(false) }
    Row(
        Modifier
            .selectableGroup()
            .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically
    ) {
        RadioButton(selected = state.value, onClick = { state.value = true })
        RadioButton(selected = !state.value, onClick = { state.value = false })
    }
}

@Composable
fun RadioButtonWithTextComponent() {
    val radioOptions = listOf("男", "女", "未知")
    val (selectedOption, onOptionSelected) = remember { mutableStateOf(radioOptions[0]) }
    Column(Modifier.selectableGroup()) {
        radioOptions.forEach { text ->
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(56.dp)
                    .selectable(
                        selected = (text == selectedOption),
                        onClick = { onOptionSelected(text) },
                        role = Role.RadioButton,
                    )
                    .padding(horizontal = 16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                RadioButton(selected = text == selectedOption, onClick = { null })
                Text(
                    text,
                    style = MaterialTheme.typography.body1.merge(),
                    modifier = Modifier.padding(start = 16.dp)
                )
            }
        }
    }
}

@Composable
fun ScrollableTabRowComponent() {
    var indexState by remember { mutableStateOf(0) }
    val titles = arrayOf("新闻", "视频", "大时代", "热点", "高考", "科技", "数码")
    Column(
        modifier = Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.Center
    ) {
        ScrollableTabRow(
            modifier = Modifier.fillMaxWidth(),
            selectedTabIndex = indexState,
            tabs = {
                titles.forEachIndexed { index, title ->
                    Tab(
                        modifier = Modifier.height(45.dp),
                        selected = index == indexState,
                        onClick = {
                            indexState = index
                        }) {
                        Text(title, fontSize = 16.sp)
                    }
                }
            }
        )

        Text(
            modifier = Modifier
                .height(150.dp)
                .fillMaxWidth(),
            textAlign = TextAlign.Center,
            text = "${titles[indexState]}"
        )

    }

}

@Composable
fun SliderComponent() {
    var sliderPosition by remember { mutableStateOf(0f) }
    var sliderPosition2 by remember { mutableStateOf(0f) }
    var finishMsg by remember { mutableStateOf("") }
    Column(Modifier.fillMaxWidth()) {

        Text(text = "当前进度：${(sliderPosition * 100).toInt()}%")
        Slider(value = sliderPosition, onValueChange = { sliderPosition = it })
        Spacer(modifier = Modifier.height(10.dp))

        Text(text = "当前进度：$sliderPosition2%  $finishMsg")
        Slider(
            value = sliderPosition2,
            onValueChange = { sliderPosition2 = it },
            valueRange = 0f..100f,
            steps = 10,
            onValueChangeFinished = {
                finishMsg = "结束"
            },
            colors = SliderDefaults.colors(
                thumbColor = MaterialTheme.colors.secondary,
                activeTickColor = MaterialTheme.colors.primary
            )
        )
    }
}

@Composable
fun SwipeToDismissList() {
    Column {
        SwipeToDismissComponent("时政")
        SwipeToDismissComponent("新闻")
        SwipeToDismissComponent("娱乐")
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun SwipeToDismissComponent(value: String) {
    var unRed by remember { mutableStateOf(false) }
    val dismissState = rememberDismissState(
        confirmStateChange = {
            if (it == DismissValue.DismissedToEnd) unRed != unRed
            it != DismissValue.DismissedToEnd
        }
    )
    SwipeToDismiss(
        state = dismissState,
        modifier = Modifier.padding(vertical = 4.dp),
        directions = setOf(DismissDirection.StartToEnd, DismissDirection.EndToStart),
        dismissThresholds = { direction -> FractionalThreshold(if (direction == DismissDirection.StartToEnd) 0.25f else 0.5f) },
        background = {
            val direction = dismissState.dismissDirection ?: return@SwipeToDismiss
            val color by animateColorAsState(
                when (dismissState.targetValue) {
                    DismissValue.Default -> Color.LightGray
                    DismissValue.DismissedToEnd -> Color.Green
                    DismissValue.DismissedToStart -> Color.Red
                }
            )
            val alignment = when (direction) {
                DismissDirection.StartToEnd -> Alignment.CenterStart
                DismissDirection.EndToStart -> Alignment.CenterEnd
            }

            val icon = when (direction) {
                DismissDirection.StartToEnd -> Icons.Default.Done
                DismissDirection.EndToStart -> Icons.Default.Delete
            }

            val scale by animateFloatAsState(targetValue = if (dismissState.targetValue == DismissValue.Default) 0.75f else 1f)
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(color)
                    .padding(horizontal = 20.dp), contentAlignment = alignment
            ) {
                Icon(icon, "", Modifier.scale(scale))
            }
        }, dismissContent = {
            Card(elevation = animateDpAsState(targetValue = if (dismissState.dismissDirection != null) 4.dp else 0.dp).value) {
                ListItem(
                    text = { Text(value, fontWeight = if (unRed) FontWeight.Bold else null) },
                    secondaryText = { Text("Swipe me left or right") })
            }
        })

}


@Composable
fun SwitchComponent() {
    var checkedState by remember { mutableStateOf(false) }
    Row {
        Text("允许4G联网", fontSize = 16.sp)
        Spacer(modifier = Modifier.padding(horizontal = 5.dp))
        Switch(checked = checkedState, onCheckedChange = { checkedState = it })
    }
}
